package com.yanglun.mvp.model.impl;

import android.content.Context;

import com.yanglun.mvp.bean.UserBean;
import com.yanglun.mvp.db.DatabaseHelper;
import com.yanglun.mvp.db.UserDBModel;
import com.yanglun.mvp.model.IUserModel;

import java.sql.SQLException;

/**
 * Created by lyang on 2016/9/13.
 */
public class UserModel implements IUserModel {
    private int id;
    private String firstName;
    private String lastName;

    @Override
    public void setID(int id) {
        this.id = id;
    }

    @Override
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Override
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @Override
    public int getID() {
        // 获取id
        return id;
    }

    /**
     * 查数据库或者联网获取id的userbean
     */
    @Override
    public UserBean load(Context context, int id) {
        try {
            DatabaseHelper dbHelper = DatabaseHelper.getHelper(context);
            UserDBModel userdbModel = dbHelper.getUserDao().queryForId(id);
            UserBean userBean = new UserBean(userdbModel.getFirstname(), userdbModel.getLastname());
            return userBean;
        } catch (SQLException e) {
            return new UserBean("null", "SQLException");
        } catch (NullPointerException e) {
            return new UserBean("null", "NullPointerException");
        }
    }

    /**
     * 存储据库或者联网数据提交
     */

    @Override
    public void save(Context context) {
        DatabaseHelper dbHelper = DatabaseHelper.getHelper(context);
        try {
            UserDBModel dbModel = new UserDBModel();
            dbModel.setFirstname(getFirstName());
            dbModel.setLastname(getLastName());
            dbModel.setId(getID());
            dbHelper.getUserDao().createOrUpdate(dbModel);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
